package com.ll.core.view.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

/**
 * 
 * 图片缓存工具
 * @author li.chh
 *
 */
public class CacheUtil {
	
	
	private static LinkedHashMap<String,Bitmap> mHardBitmapCache = new LinkedHashMap<String,Bitmap>(){
		 private static final int MAX_ENTRIES = 10;
		 /**
		  * 当缓存中的缓存的图片数量大于10,清空缓存.
		  */
	     protected boolean removeEldestEntry(Map.Entry eldest) {
	        return size() > MAX_ENTRIES;
	     }

	};
	
	private static CacheUtil cacheUtil;
	
	public static CacheUtil getInstance(){
		
		if(cacheUtil == null){
			cacheUtil = new CacheUtil();
		}
		return cacheUtil;
	}
	
	/**
	 * 将图片信息保存到缓存
	 * @param bm
	 * @param filename
	 */
	public void saveImgToCache(Bitmap bitmap, String filename){
		synchronized (mHardBitmapCache) {  
			mHardBitmapCache.put(filename, bitmap);
		}
		saveBmpToSd(filename,bitmap);
	}
	
	
	/**
	 * 将图片信息保存到sd卡中
	 * @param bm
	 * @param filename
	 */
	private  void saveBmpToSd(String filename,Bitmap bm) {
		String TAG = "保存图片到SD";
		if (bm == null) {
			Log.w(TAG, " trying to savenull bitmap");
			return;
		}
		// 判断sdcard上的空间
//		if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
//			Log.w(TAG, "Low free space onsd, do not cache");
//			return;
//		}
		// String filename =convertUrlToFileName(url);
		// String dir = getDirectory(filename);
		String dir = getImgCachePath();
		this.makedir(dir);
		Log.w(TAG, "获取图片缓存路径"+dir);
		File file = new File(dir + filename);
		try {
		Log.w(TAG, "创建文件"+file.toString());
			file.createNewFile();
			OutputStream outStream = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			outStream.flush();
			outStream.close();
			Log.i(TAG, "Image saved tosd");
		} catch (FileNotFoundException e) {
			Log.w(TAG, "FileNotFoundException");
		} catch (IOException e) {
		    e.printStackTrace();
			Log.w(TAG, "IOException");
		}
	}

	private int freeSpaceOnSd() {
//		StatFs stat = newStatFs(Environment.getExternalStorageDirectory()
//				.getPath());
//		double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
//				.getBlockSize()) / MB;
//		return (int) sdFreeMB;
		return 0;
	}
	/**
	 * 获得缓存的路径
	 * @return
	 */
	public  String getCachePath(){
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		}else{
			sdDir = Environment.getDataDirectory();
		}
		System.out.println("getExternalStorageDirectory():   "
				+ sdDir.toString());
		return sdDir+"/edp/cache/";
	}
	public  String getImgCachePath(){
		return getCachePath()+"imgs/";
	}
    /** 
     * 从缓存中获取图片 
     * @throws Exception 
     */  
    public  Bitmap getBitmapFromCache(String filename) throws Exception {  
    	Bitmap bitmap = null;
        // 先从mHardBitmapCache缓存中获取  
        synchronized (mHardBitmapCache) {  
            bitmap =mHardBitmapCache.get(filename);  
            if (bitmap != null) {  
                //如果找到的话，把元素移到linkedhashmap的最前面，从而保证在LRU算法中是最后被删除  
                mHardBitmapCache.remove(filename);  
                mHardBitmapCache.put(filename,bitmap); 
                Log.w("获取图片", "从内存中获取图片"+filename+bitmap.toString());
                return bitmap;  
            }  
        }
        //从sd卡中获取缓存的图片信息
        if(bitmap == null){
        	String dir = getImgCachePath();
    		this.makedir(dir);
    		
        	bitmap  = LoadBitmapFromCache(dir+ filename);
        	 //如果找到的话，把元素移到linkedhashmap的最前面，从而保证在LRU算法中是最后被删除  
        	//放入到缓存里面 
            mHardBitmapCache.put(filename,bitmap);  
        	Log.w("获取图片", "从sd卡获取图片"+filename+bitmap.toString());
        	return bitmap;
        }
//        //如果mHardBitmapCache中找不到，到mSoftBitmapCache中找  
//        SoftReference<Bitmap> bitmapReference = mSoftBitmapCache.get(filename);  
//        if (bitmapReference != null) {  
//            final Bitmap bitmap =bitmapReference.get();  
//            if (bitmap != null) {  
//                return bitmap;  
//            } else {  
//                mSoftBitmapCachemove(filename);  
//            }  
//        }  
        return bitmap;  
    }  
    
    public Bitmap LoadBitmapFromCache(String filename) throws Exception{
    	File file = new File(filename);
    	if(!file.exists()){
    		return null;
    	}
    	FileInputStream fis =new java.io.FileInputStream(filename);
    	Bitmap bitmap = BitmapFactory.decodeStream(fis);
		// 关闭数据流
    	fis.close();
    	return bitmap;
    }
    /**
     * 创建文件夹
     * 
     * @param dir 文件夹
     */
    public void makedir(String dir){
    	File filedir = new File(dir);
    	if(!filedir.exists()){
    		filedir.mkdirs();
    		Log.d("创建目录", "创建目录"+dir+filedir.exists());
    	}
    }
	public void getSDPath() {
		File sdDir = null;
		File sdDir1 = null;
		File sdDir2 = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
			sdDir1 = Environment.getDataDirectory();
			sdDir2 = Environment.getRootDirectory();
		}
		System.out.println("getExternalStorageDirectory():   "
				+ sdDir.toString());
		System.out.println("getDataDirectory():  " + sdDir1.toString());
		System.out.println("getRootDirectory():  " + sdDir2.toString());
	}
}
